<link rel="stylesheet" href="/css/jquery-ui.css" />
<?php
$db = new Database();
$auth = Auth::getAuth('current_user');
$userCompany = new userQueries();
$company = $userCompany->getCompany($auth['company_id']);
$upload = new upload();

$personDoc = new Person($db, $auth['id']);
$userDepartmentName = $personDoc->department->name;
$formDoc = new Form($db, $_GET['formID']);

$application_id = $_COOKIE['application'];

// $YEAH_FORMULA = new Formula("@Department[Requestor] + @TrackNo + @DEPARTMENTFIELD");
// print_r($YEAH_FORMULA->setSourceForm("DYNAMIC_TABLE_TESTING","*",array("TESTING3DIGIT"=>"JC000") ) );
// print_r($YEAH_FORMULA->getProccessedFormula());
// $YEAH_FORMULA = new Formula("@Lookup('DYNAMIC_TABLE_TESTING' , 'TrackNo')");
// print_r($YEAH_FORMULA->getProccessedFormula());
// $YEAH_FORMULA = new Formula("@Concat('DYNAMIC_TABLE_TESTING' , 'TrackNo','biscuites')");
// print_r($YEAH_FORMULA->getProccessedFormula());
// print_r(eval($YEAH_FORMULA->getProccessedFormula()));
$displayPreviewStyle = "";
if ($_GET['view_type'] == "preview") {
    $formWidth = $_GET['formWidth'];
    $formHeight = $_GET['formHeight'];
    $form_container = "style='margin: 0px auto;width:" . $formWidth . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $formHeight . "px;'";
    $displayPreviewStyle = "display:none !important;";
} elseif ($_GET['view_type'] == "request" || $_GET['view_type'] == "report") {
    // Get Workspace Information
    $getID = $_GET['formID'];
    $requestID = $_GET['requestID'];

    $str = "SELECT WS.*, WFO.workflow_id, WFO.buttonStatus,WFO.fieldEnabled, WFO.fieldRequired, WFO.fieldHiddenValue FROM tb_workspace WS 
                           LEFT JOIN tbworkflow WF
                            ON WS.Id = WF.form_id 
                           LEFT JOIN tbworkflow_objects WFO
                            ON WFO.workflow_id = WF.id 
                            WHERE WS.id={$db->escape($getID)} AND WFO.type_rel = '1'  AND WF.Is_Active = '1'";
    $form = $db->query($str, "row");


    $form_json = json_decode($form['form_json'], true);

    $form_container = "style='margin: 0px auto;width:" . $form_json['WorkspaceWidth'] . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $form_json['WorkspaceHeight'] . "px;'";

    $fieldEnabled = $form['fieldEnabled'];
    $fieldRequired = $form['fieldRequired'];
    $fieldHiddenValues = $form['fieldHiddenValue'];
} elseif ($_GET['view_type'] == "update") {
    // Get Workspace Information
    $getID = $_GET['ID'];
    $requestID = $_GET['requestID'];

    $str = "SELECT WS.*, WFO.workflow_id, WFO.buttonStatus,WFO.fieldEnabled, WFO.fieldRequired, WFO.fieldHiddenValue FROM tb_generate WS 
                           LEFT JOIN tbworkflow WF
                            ON WS.form_id = WF.form_id 
                           LEFT JOIN tbworkflow_objects WFO
                            ON WFO.workflow_id = WF.id 
                            WHERE WS.id={$db->escape($getID)} AND WFO.type_rel = '1'  AND WF.Is_Active = '1'";
    $form = $db->query($str, "row");


    $form_json = json_decode($form['form_json'], true);

    $form_container = "style='margin: 0px auto;width:" . $form_json['WorkspaceWidth'] . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $form_json['WorkspaceHeight'] . "px;'";

    $fieldEnabled = $form['fieldEnabled'];
    $fieldRequired = $form['fieldRequired'];
    $fieldHiddenValues = $form['fieldHiddenValue'];
}
$request_view_datas = createRequestView($_GET);

// Get form name
$form_name = $form['form_table_name'];
$request_details = $db->query("SELECT * FROM " . $form_name . " WHERE ID={$db->escape($_GET['requestID'])}","row");
$requestor_details = $db->query("SELECT * FROM tbuser WHERE id={$db->escape($request_details['Requestor'])}","row");
$get_processor_details = $db->query("SELECT * FROM `tbuser` WHERE id IN (" . $request_view_datas["auth_id"] . ") AND is_active={$db->escape(1)}","row");
?>
<style class="append-script-design"></style>

<div class="bgs-header"></div>
 <?php if ($_GET['view_type'] == "preview") {
    echo "<h1 style='text-align:center;'>Workspace Preview </h1>"; }
  ?>
<br/><br/>
<h1 class="form-name-title"><?php echo $request_view_datas["form_name"]; ?></h1>
<br/>
<br/>
<div class="fl-form-wrapper" style="margin-top: -10px;height:auto;">
    <div class="fl-head-title-wrapper" style="float: left;width: 100%; padding:5px; box-sizing:border-box;">
        <!-- ========== Attachmemt Files ========== -->
        <div class="padding_5 attached_file_container pr-nodes">

            <?php
            /* ========== Get Attachment files ========== */
            $path = "images/attachment";
            if(isset($_GET['trackNo'])){
                $trackNo = $_GET['trackNo'];
            }else{
                $trackNo = $request_details['TrackNo'];
            }
            $id_encrypt = md5(md5($trackNo));
            $dir = $path . "/" . $id_encrypt;
            /* ========== Get all files from the directory ========== */
            $getAttachment = $upload->getAllfiles_fromDirectory($dir);
            /* ========== List of files ========== */
            foreach ($getAttachment as $files) {
                $get_extension = explode(".", $files);
                $extension = $get_extension[count($get_extension) - 1];
                /* ========== Determine if files is an image or not ========== */
                $formats = array("jpg", "png", "JPG", "PNG", "GIF", "gif");
                if (!in_array($extension, $formats)) {
                    echo '<div>';
                    echo '<form class="pull-left" method="POST" >';
                    echo '<div>';
                    echo '<input type="submit" class="cursor tip" data-original-title="Download Attachment"/><i class="fa fa-download"></i> ';
                    echo '<i class="fa fa-trash-o cursor tip removeFiles" data-original-title="Remove Attachment" data-file="' . $files . '" data-location="' . $dir . '/' . $files . '"></i>';
                    echo '</div>';
                    echo '<a class="download_attachment">';
                    echo '<div data-name="' . $files . '" class="AFiles_only avatar AFiles tip" data-original-title="' . $files . '" title="' . $files . '"><i class="fa fa-file"></i></div>';
                    echo '</a>';
                    //echo '<input type="submit"/>';
                    echo '<input type="hidden" value="' . $files . '" name="attachment_filename"/>';
                    echo '<input type="hidden" value="' . $dir . '/' . $files . '" name="attachment_location"/>';

                    echo '</form>';
                    echo '</div>';
                } else {
                    echo '<div style="float:left;background-color:#fff;border:1px solid #D5D5D5;border-radius:5px;padding:5px;margin-left:5px;min-height:40px;">';
                    echo '<form class="pull-left" method="POST">';
                    echo '<div style="text-align: center;">';
                    echo '<input type="submit" style="opacity: 0;position: absolute;width: 10px;" class="cursor tip" data-original-title="Download Attachment"/><i class="fa fa-download"></i> ';
                    echo '<i class="fa fa-trash-o cursor tip removeFiles" data-original-title="Remove Attachment" data-file="' . $files . '" data-location="' . $dir . '/' . $files . '"></i>';
                    echo '</div>';
                    echo '<a class="download_attachment">';
                    echo '<img data-name="' . $files . '" src="/' . $dir . '/' . $files . '" width="25" height="25" class="AFiles imagetoPost avatar userPhoto personalPhoto userAvatar" data-original-title="' . $files . '" title="' . $files . '">';
                    echo '</a>';
                    //echo '<input type="submit"/>';
                    echo '<input type="hidden" value="' . $files . '" name="attachment_filename"/>';
                    echo '<input type="hidden" value="' . $dir . '/' . $files . '" name="attachment_location"/>';
                    echo '</form>';
                    echo '</div>';
                }
            }
            ?>

        </div>
        <?php
        if (count($getAttachment) != "0") {
            echo '<br /><br />';
        }
        ?>
    </div>
    <?php if ($_GET['view_type'] != "preview") { ?>
    <div class="fl-head-title-wrapper form-action-navs" style="width: 100%;">

        <div class="title_head_btn">
            <div class="btn-basicBtn  fl-backhistory fl-createViewreq fl-buttonEffect padding_5 cursor tip" data-placement="bottom" data-original-title="Go back"><i class="fa fa-reply" style="color:#ffffff;"></i></div>
            <?php
            if ($_GET['view_type'] != "update") {
                if ($_GET['requestID'] != 0) {
                    echo '<div class="btn-basicBtn padding_5 fl-createViewreq fl-buttonEffect cursor showReply tip"  data-placement="bottom" data-type="1" data-f-id="' . $_GET['formID'] . '" data-id="' . $requestID . '" data-original-title="Add/View Comments"><i class="fa fa-comment"></i></div> ';
                }
            echo '<div style="'. $displayPreviewStyle .'  float:left;">';
            echo '<div class="btn-basicBtn fl-createViewreq fl-buttonEffect padding_5 cursor tip viewAuditLogs" data-placement="bottom" data-original-title="View Logs"><i class="fa fa-book"></i></div> ';
            echo '<div class="btn-basicBtn fl-createViewreq fl-buttonEffect padding_5 cursor tip printForm" data-placement="bottom" data-original-title="Print Form"><i class="fa fa-print"></i></div> ';
            
                if(!functions::getPinnedRequest($getID,$requestID)){
                 echo '<div class="btn-basicBtn fl-createViewreq fl-buttonEffect padding_5 cursor tip request_dashboard_pin" fl-data-application-id="' . $application_id . '" data-placement="bottom" data-original-title="Pin this to dashboard"><i class="fa fa-thumb-tack"></i></div> ';
                }
            }
            if ($_GET['view_type'] != "update") {
            echo '<span class="viewer_action"></span> ';
            echo '<div class="btn-basicBtn fl-createViewreq fl-buttonEffect padding_5 cursor tip uploadButtonRequest" data-placement="bottom" data-original-title="Add Files">';
            echo '<form id="fille_attach" method="post" enctype="multipart/form-data" action="/ajax/request_attachment">';
            echo '<input type="file" data-action-id="2" value="upload" name="file" id="file" size="24" data-action-type="attachFile" style="width: 10px;opacity: 0;position:absolute;" class="cursor upfile">';
            echo '<input type="text" name="getFormID" id="getFormID" value="' . $_GET['formID'] . '" data-type="longtext" class="display getFields" />';
            echo '<input type="text" name="getID" id="getID" value="' . $_GET['requestID'] . '" data-type="longtext" class="display getFields" />';
            echo '<input type="text" name="getTrackNo" id="getTrackNo" value="' . $trackNo . '" data-type="longtext" class="display getFields" />';
            echo '<i class="fa fa-paperclip"></i>';
            echo '</form></div> ';
            echo '<img src="/images/loader/load.gif" class="display attachFiles"/>';
            echo '</div>';
            }else{
                echo '<div class="btn-basicBtn fl-createViewreq fl-buttonEffect padding_5 cursor tip printForm" data-placement="bottom" data-original-title="Print Form"><i class="fa fa-print"></i></div> ';
            }
            ?>


        </div>
        <?php
        if ($_GET['view_type'] != "update") {
        ?>
        <div class="fl-head-menu-wrapper" style="<?php echo $displayPreviewStyle; ?>">
            <ul class="fl-head-menu">   
                <li id="fl-action-btn"><a href="#" style="color:white;">Actions <i class="fa fa fa-chevron-right"></i></a></li> 
            </ul>
            <ul id="fl-action-option" style="z-index:1;">
                <?php echo $request_view_datas["action_buttons"]; ?>
            </ul>
        </div>
        <?php
        }
        ?>
        <div class="clearfix"></div>
    </div>
    <?php } ?>
    <div class="fl-body-content-wrapper preview_content">
        <form id="frmrequest" method="POST" action="/ajax/request" data-type="" style="display:inline-block;position:relative;width:100%;height:100%;">
            <div class="display">
                <!-- INPUT FIELD STANDARDS -->
                <input type="text" name="FormAuthEmail" id="FormAuthEmail" value="<?php echo $auth['email']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="FormAuthID" id="FormAuthID" value="<?php echo $auth['id']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="FormID" id="FormID" value="<?php echo $_GET['formID']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="FormName" id="FormName" value="<?php echo $formDoc->form_name; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="WorkflowId" id="WorkflowId" value="<?php echo $request_view_datas["workflow_id"]; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="ID" id="ID" value="<?php echo $_GET['requestID']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="TrackNo" id="TrackNo" value="<?php echo $trackNo; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="Requestor" requestor-name="<?php echo $request_view_datas["auth_display_name"]; ?>" value="<?php echo $request_view_datas["auth_id"]; ?>" id="Requestor" data-type="longtext" class="getFields" />
                <input type="text" name="CurrentUser" current-user-name="<?php echo $request_view_datas["auth_display_name"]; ?>" value="<?php echo $request_view_datas["auth_id"]; ?>" id="CurrentUser" data-type="longtext" class="getFields" />
                <input type="text" name="Status" id="Status" value="<?php echo $request_details['status']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="request_by" id="request_by" value="<?php echo $requestor_details['display_name']; ?>" data-type="longtext" class="getFields" />
                <input type="text" name="processor_by" id="processor_by" value="<?php echo $get_processor_details['display_name']; ?>" data-type="longtext" class="getFields" />
                
                
                <input type="text" name="Processor" value="<?php echo $request_view_datas["auth_id"]; ?>" processor-name="<?php echo $request_view_datas["auth_display_name"]; ?>" id="Processor" data-type="longtext" class="getFields" />
                <input type="text" name="LastAction" id="LastAction" value='<?php echo $request_view_datas["buttonStatus"]; ?>' data-type="longtext" class="getFields" />
                <input type="text" name="DateCreated" id="DateCreated" data-type="longtext" class="getFields" />
                <input type="text" name="DateUpdated" id="DateUpdated" data-type="longtext" class="getFields" />
                <input type="text" name="CreatedBy" value="<?php echo $request_view_datas["auth_id"]; ?>" id="CreatedBy" data-type="longtext" class="getFields" />
                <input type="text" name="UpdatedBy" value="<?php echo $request_view_datas["auth_id"]; ?>" id="UpdatedBy" data-type="longtext" class="getFields" />
                <input type="text" name="Unread" id="Unread" data-type="longtext" class="getFields" />
                <input type="text" name="Node_ID" id="Node_ID" data-type="longtext" class="getFields" />
                <input type="text" name="Workflow_ID" id="Workflow_ID" data-type="longtext" class="getFields" />
                <input type="text" name="Mode" id="Mode" value="formApproval" data-type="longtext" class="getFields" />
                <input type="text" name="imported" id="imported" data-type="longtext" class="getFields" />
                <input type="text" name="computedFields" id="computedFields" />
                <input type="text" name="fieldEnabled" id="fieldEnabled" value=' <?php echo $request_view_datas["fieldEnabled"]; ?> ' data-type="longtext" class="getFields" />
                <input type="text" name="KeywordsField" id="KeywordsField" data-type="longtext" class="" />
                <input type="text" name="Repeater_Data" value="<?php echo $request_view_datas["Repeater_Data"]; ?>" id="Repeater_Data" data-type="longtext" class="" />
                <input type="text" name="Department_Name" value="<?php echo $request_view_datas["userDepartmentName"]; ?>" id="Department_Name" data-type="longtext" class="" />
                <input type="text" name="Editor" value="<?php echo $request_view_datas["Editor"]; ?>" id="Editor" data-type="longtext" class="" />
            
                <!-- ========== GET FIELD ENABLED, FIELD REQUIRED AND FIELD HIDDEN VALUES ========== -->
                <div class="fieldEnabled"><?php echo $request_view_datas["fieldEnabled"]; ?></div>
                <div class="fieldRequired"><?php echo $request_view_datas["fieldRequired"]; ?></div>
                <div class="fieldHiddenValues"><?php echo $request_view_datas["fieldHiddenValues"]; ?></div>

                <div class="fieldEnabled_default"><?php echo $request_view_datas["fieldEnabled"]; ?></div>
                <div class="fieldRequired_default"><?php echo $request_view_datas["fieldRequired"]; ?></div>
                <div class="fieldHiddenValues_default"><?php echo $request_view_datas["fieldHiddenValues"]; ?></div>
                <input type="text" class="preview-nodes" value="<?php
                if (isset($_GET['type']) && $_GET['type'] == "flowchart" || $_GET['type'] == "orgchart") {
                    echo "true";
                } else {
                    echo "false";
                }
                ?>">
                <!-- ========== Files Json ========== -->
                <input type="text" name="attachment_files" id="view_attachment_files" />
            </div>
            <?php
            if ($_GET['requestID'] != "0") {
                $display_form_status = "display:block;";
            } else {
                $display_form_status = "display:none;";
            }
            ?>
            <div class="display_form_status" style="<?php echo $display_form_status; ?>width:auto;position:relative; padding:5px;<?php echo $displayPreviewStyle; ?>">
                <ul style="display:inline-block;width:100%;">
                    <li style="padding: 10px 0px;float:left;display:inline-block;"><label ><b>Tracking Number:</b><u><span id="trackno_display">______</span></u></label></li>
                    <li style="padding: 10px 0px;float:left;display:inline-block;"><label ><b>Requestor:</b><u><span id="requestor_display">______</span></u></label></li>
                    <li style="padding: 10px 0px;float:right;display:inline-block;"><label ><b>Processor:</b><u><span id="processor_display">______</span></u></label></li>
                    <li style="padding: 10px 0px;float:right;display:inline-block;"><label ><b>Status:</b><u><span id="status_display">______</span></u></label></li>
                </ul>
            </div>

            <div class="loaded_form_content" style="margin:0px auto;position:relative;width:<?php echo ( ($form_json['WorkspaceHeight'] )?$form_json['WorkspaceHeight']:$request_view_datas["form_size"]["width"]); ?>px;height:<?php echo ( ($form_json['WorkspaceHeight'])?$form_json['WorkspaceHeight']:$request_view_datas["form_size"]["height"]); ?>px;background-color:rgb(240,240,240);">
                <script>
                    $(document).ready(function(){
                        var path_name = window.location.pathname;
                        //if (path_name == "/user_view/workspace" && getParametersName("view_type", pathname) == "update") {
                            var requestor_id = $("#request_by").val();
                            //var status = $("#Status").val();
                            //var trackNO = $("#TrackNo").val();
                            ////var requestor_id = $("#Requestor").attr('requestor-name');
                            //$("#requestor_display").html(requestor_id);
                            //$("#trackno_display").html(trackNO);
                            //$("#status_display").html(status);
                        //}
                    });
                    var pathname = window.location;
                    if (getParametersName("view_type", pathname) == "preview" || getParametersName("view_type", pathname) == "report") {
                        
                        var pid = window.opener["pid"];
                        var parseJson_data = jQuery.parseJSON(pid);
                        // Btn Content
                        var workspace_btn = parseJson_data.BtnName;
                        var get_btn = workspace_btn.split(",");
                        for (var a = 0; a < get_btn.length; a++) {
                            $(".input-select").append("<option>" + get_btn[a] + "</option>");
                        }
                        // Form Content   
                        var workspace_content = parseJson_data.WorkspaceContent;
                        var content = workspace_content.replace(new RegExp("setObject cursor_move", "g"), "setOBJ form_upload_photos").replace(new RegExp('disabled="disabled"', 'g'), "");
                        //console.log(content)
                        // Append To content preview form
                        $(".loaded_form_content").append(content);
                        $(".formName").hide();
                        $(".fl-content").css("width", "100%");
                    }
                    //});
                </script>
                <?php
                echo $request_view_datas["form_content"];
                ?>
                <script>
                    $(document).ready(function(){
                        var path_name = window.location.pathname;
                        if (path_name == "/user_view/workspace" && getParametersName("view_type", pathname) == "update") {
                            $(".getFields").each(function(){
                                $(this).attr('disabled',true);
                            });
                        }
                    });
                </script>
            </div>
        </form>
    </div>
</div>